"""
JWT token的解析和刷新逻辑
"""
import jwt
from typing import Dict, Optional, Any
from datetime import datetime, timedelta
from config.settings import settings
from common.logger import get_logger

logger = get_logger(__name__)


class JWTTokenHandler:
    """JWT Token处理器"""
    
    def __init__(self):
        self.secret_key = settings.get("auth.jwt_secret", "default-secret-key")
        self.algorithm = settings.get("auth.algorithm", "HS256")
        self.expire_hours = settings.get("auth.token_expire_hours", 24)
    
    def create_access_token(self, data: Dict[str, Any]) -> str:
        """创建访问token"""
        to_encode = data.copy()
        expire = datetime.utcnow() + timedelta(hours=self.expire_hours)
        to_encode.update({"exp": expire})
        
        encoded_jwt = jwt.encode(to_encode, self.secret_key, algorithm=self.algorithm)
        logger.info(f"创建访问token，用户: {data.get('user_id', 'unknown')}")
        return encoded_jwt
    
    def create_refresh_token(self, data: Dict[str, Any]) -> str:
        """创建刷新token（有效期更长）"""
        to_encode = data.copy()
        expire = datetime.utcnow() + timedelta(days=30)  # 30天有效期
        to_encode.update({"exp": expire, "type": "refresh"})
        
        encoded_jwt = jwt.encode(to_encode, self.secret_key, algorithm=self.algorithm)
        logger.info(f"创建刷新token，用户: {data.get('user_id', 'unknown')}")
        return encoded_jwt
    
    def verify_token(self, token: str) -> Optional[Dict[str, Any]]:
        """验证token并返回payload"""
        try:
            payload = jwt.decode(token, self.secret_key, algorithms=[self.algorithm])
            return payload
        except jwt.ExpiredSignatureError:
            logger.warning("Token已过期")
            return None
        except jwt.InvalidTokenError as e:
            logger.warning(f"无效的token: {e}")
            return None
    
    def decode_token(self, token: str) -> Optional[Dict[str, Any]]:
        """解码token（不验证过期）"""
        try:
            payload = jwt.decode(token, self.secret_key, algorithms=[self.algorithm], options={"verify_exp": False})
            return payload
        except jwt.InvalidTokenError as e:
            logger.warning(f"解码token失败: {e}")
            return None
    
    def is_token_expired(self, token: str) -> bool:
        """检查token是否过期"""
        payload = self.decode_token(token)
        if not payload:
            return True
        
        exp_timestamp = payload.get("exp")
        if not exp_timestamp:
            return True
        
        expire_time = datetime.fromtimestamp(exp_timestamp)
        return expire_time < datetime.utcnow()
    
    def get_token_expiry(self, token: str) -> Optional[datetime]:
        """获取token过期时间"""
        payload = self.decode_token(token)
        if payload and "exp" in payload:
            return datetime.fromtimestamp(payload["exp"])
        return None
    
    def refresh_access_token(self, refresh_token: str) -> Optional[str]:
        """使用刷新token获取新的访问token"""
        payload = self.verify_token(refresh_token)
        if not payload or payload.get("type") != "refresh":
            logger.warning("无效的刷新token")
            return None
        
        # 创建新的访问token
        access_token_data = {
            "user_id": payload.get("user_id"),
            "username": payload.get("username"),
            "roles": payload.get("roles", [])
        }
        
        return self.create_access_token(access_token_data)
    
    def validate_token_structure(self, token: str) -> bool:
        """验证token结构"""
        try:
            # 尝试解码但不验证签名
            jwt.decode(token, options={"verify_signature": False})
            return True
        except jwt.DecodeError:
            return False


# 全局JWT处理器实例
jwt_handler = JWTTokenHandler()